<template>
  <div class="app-container home">
    <!-- 设置行高为100%，确保列可以继承高度 -->
    <el-row :gutter="20" class="equal-height-row">
      <!-- 第一列 -->
      <el-col :span="6" class="equal-height-col">
        <el-card class="box-card h-full">
          <template #header>
            <div class="card-header">今日礼金金额</div>
          </template>
          <div class="money-info">
            <el-row >
              <el-col  :span="10">
                <p class="large-money">¥ {{payAmountWeekEntity.todayAmount}}</p>
              </el-col>
              <el-col :span="4">
                <div class="day-count">
                  <p class="small-text">共{{payAmountWeekEntity.todayPayCount}}笔</p>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--          -->
          <div class="seven_day_chart">
            <v-chart :option="sevenDayChart" :autoresize="true" />
          </div>
          <div class="sub-info">
            <el-row >
              <el-col  :span="12">
                <p>昨日礼金金额：¥{{payAmountWeekEntity.yesterdayAmount}}</p>
              </el-col>
              <el-col :span="12">
                <p>近七天礼金金额：¥{{payAmountWeekEntity.payWeek}}</p>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <!-- 第二列（包含两个卡片） -->
      <el-col :span="5" class="equal-height-col">
        <div class="card-group h-full flex flex-col gap-4">
          <el-card class="box-card flex-1">
            <template #header>
              <div class="card-header">礼金总金额</div>
            </template>
            <div class="large-money">¥{{numCountEntity.totalAmount}}</div>
          </el-card>
          <el-card class="box-card flex-1">
            <template #header>
              <div class="card-header">礼金总笔数</div>
            </template>
            <div class="large-money">{{numCountEntity.totalCount}} 笔</div>
          </el-card>
        </div>
      </el-col>

      <!-- 第三列（包含两个卡片） -->
      <el-col :span="3" class="equal-height-col">
        <div class="card-group h-full flex flex-col gap-4">
          <el-card class="box-card flex-1">
            <template #header>
              <div class="card-header">礼簿数量</div>
            </template>
            <div class="large-money">{{numCountEntity.totalBooks}}</div>
          </el-card>
          <el-card class="box-card flex-1">
            <template #header>
              <div class="card-header">用户数量</div>
            </template>
            <div class="large-money">{{numCountEntity.totalUser}}</div>
          </el-card>
        </div>
      </el-col>

      <!-- 第四列 -->
      <el-col :span="10" class="equal-height-col">
        <el-card class="box-card h-full">

        </el-card>
      </el-col>
    </el-row>
    <!-- 第二行 - 添加了行间距样式 -->
    <el-row :gutter="20" class="second-equal-height-row row-margin">
      <el-col :span="16" class="equal-height-col">
        <el-card class="box-card h-full">
          <template #header>
            <div class="card-header">礼金统计</div>
          </template>
          <div class="chart-container">
            <v-chart :option="tradeDay" :autoresize="true" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" class="equal-height-col">
        <el-card class="box-card h-full">
          <template #header>
            <div class="card-header">统计</div>
          </template>
          <!--图标容器测试-->
          <div class="chart-container" >
            <v-chart ref="tradeDayPieEvent" :option="tradeDayPie" :autoresize="true"
                     @mouseover="handleMouseOver"
                     @mouseout="handleMouseOut" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index">
  import {numCount, payAmountWeek, payCount, payTypeCount} from '@/api/book/dashboard.js'

  const version = ref('3.9.0')
  const payAmountWeekEntity = ref({
    todayAmount: 0.00,
    todayPayCount: 0.00,
    yesterdayAmount: 0.00,
    payWeek: 0.00,
    dateArray: []
  })
  const numCountEntity = ref({
    totalAmount: '0.00',
    totalCount: 0,
    totalBooks: 0,
    totalUser: 0,
  })
  // 7天迷你收入折线图
  const sevenDayChart = ref({
    grid: {
      left: 5,
      right: 5,
      top: 0,
      bottom: 0,
      containLabel: false
    },
    tooltip: {
      trigger: 'axis', // 鼠标悬停显示提示
      axisPointer: {
        type: 'line'  // 确保axisPointer配置正确
      },
      formatter: function(params) {
        // 确保params存在且有数据
        if (!params || params.length === 0) return '';
        const amount = Number(params[0].value).toFixed(2);
        return `${amount}`;
      },
    },
    xAxis: {
      boundaryGap: false,
      type: 'category',
      data:  [],
      show: false // 隐藏x轴，适合小型图表
    },
    yAxis: {
      type: 'value',
      show: false // 隐藏y轴，适合小型图表
    },
    series: [
      {
        name: '金额',
        data:  [],
        type: 'line',
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(54, 162, 235, 0.6)' },
              { offset: 1, color: 'rgba(54, 162, 235, 0)' }
            ]
          }
        },
        lineStyle: {
          width: 2,
          color: 'rgba(54, 162, 235, 1)'
        },
        symbol: 'none' // 隐藏数据点
      }
    ]
  })
  // 7柱状图
  const tradeDay = ref({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow' // 阴影指示器，方便同时选中同组柱子
      },
      // 格式化tooltip，同时显示两条数据
      formatter: function(params) {
        let result = '';
        // 遍历当前组的所有数据（收入和支出）
        params.forEach(item => {
          result += item.seriesName + '：' + item.value + '<br>';
        });
        return result;
      }
    },// 图例配置
    legend: {
      orient: 'horizontal',
      left: 10,
      data: ['收入', '支出']
    },
    xAxis: {
      type: 'category',
      data:  ["1号", "2号", "3号", "4号", "5号","6号","7号"],
      show: true
    },
    yAxis: {
      type: 'value',
      show: true
    },
    series: [
      { name: '收入',
        data:  [213459, 150000, 205000, 200000, 195000, 155000, 195000],
        type: 'bar',
      },
      {
        name: '支出',
        data:  [13459, 50000, 5000, 2000, 19500, 55000, 95000],
        type: 'bar',
      }
    ]
  })
  // 7饼图
  const tradeDayPie = ref({
    // 标题配置
    title: {
      text: '总计\n0.00元',
      left: '50%',
      top: '50%',
      textAlign: 'center',
      textVerticalAlign: 'middle',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },

    // 提示框配置
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },

    // 图例配置
    legend: {
      orient: 'vertical',
      left: 10,
      data: []
    },

    // 系列配置 - 中心透明的关键
    series: [
      {
        name: '支付渠道',
        type: 'pie',
        radius: ['50%', '80%'], // 内外半径设置，形成透明中心
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10, // 圆角效果
          borderColor: '#fff', // 白色边框分隔
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'inside', // 标签位置在外侧
          formatter: '{c}', // 显示金额
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  })

  const tradeDayPieAllTitle = ref('总计\n0.00元')

  function getPayAmountWeek() {
    payAmountWeek().then(response=>{
      response.data.todayAmount = Number(response.data.todayAmount).toFixed(2)
      response.data.yesterdayAmount = Number(response.data.yesterdayAmount).toFixed(2)
      response.data.payWeek = Number(response.data.payWeek).toFixed(2)
      payAmountWeekEntity.value = response.data

      sevenDayChart.value.xAxis.data = payAmountWeekEntity.value.dateArray.map(v => v.payDate)
      sevenDayChart.value.series[0].data = payAmountWeekEntity.value.dateArray.map(v => Number(v.payAmount).toFixed(2))
    })
  }

  function getNumCount() {
    numCount().then(response=>{
      response.data.totalAmount = Number(response.data.totalAmount).toFixed(2)
      numCountEntity.value = response.data
    })
  }
  function getPayCount() {
    payCount().then(response=>{
      let data = response.data;
      tradeDay.value.xAxis.data = data.pay.map(v=>v.payDate.substring(5))
      tradeDay.value.series[0].data = data.pay.map(v=>Number(v.payAmount).toFixed(2))
      tradeDay.value.series[1].data = data.refund.map(v=>Number(v.payAmount).toFixed(2))
    })
  }
  function getPayTypeCount() {
    payTypeCount().then(response=>{
      let data = response.data;

      const totalAmount = data.reduce((sum, item) => {
        return sum + item.payAmount; // 累加当前项的value到总和中
      }, 0).toFixed(2); // 初始值为0
      tradeDayPieAllTitle.value = `总计\n${totalAmount} 元`

      tradeDayPie.value.title.text = tradeDayPieAllTitle.value
      tradeDayPie.value.legend.data = data.map(v=>v.label)
      tradeDayPie.value.series[0].data = data.map(v => {
        let itemStyle = {color: '#73C0DE'};
        if (v.label === '支付宝') {
          itemStyle = {color: '#5470C6'};
        } else if (v.label === '微信') {
          itemStyle = {color: '#91CC75'};
        } else if (v.label === '现金') {
          itemStyle = {color: '#FAC858'};
        }
        return {
          value: Number(v.payAmount).toFixed(2),
          name: v.label,
          itemStyle
        }
      });
    })
  }

  // 鼠标移到元素上的事件处理
  const handleMouseOver = (params) => {
    tradeDayPie.value.title.text  = `${params.name}\n${params.value} 元`
  };

  // 鼠标移出元素的事件处理
  const handleMouseOut = (params) => {
    tradeDayPie.value.title.text  = tradeDayPieAllTitle.value
  };

  getPayCount()
  getPayAmountWeek()
  getNumCount()
  getPayTypeCount()
</script>

<style scoped lang="scss">
.home {
  background: #fafafa;
}
.app-container {
  padding: 20px;
}
.seven_day_chart {
  height: 90px;
}
/* 关键样式：设置行和列的高度为100% */
.equal-height-row {
  height: 260px; /* 固定行高度，可根据需要调整 */
}
.second-equal-height-row {
  height: 420px; /* 固定行高度，可根据需要调整 */
}
/* 行间距样式 - 主要修改点 */
.row-margin {
  margin-top: 20px; /* 第一行和第二行之间的距离 */
}

.equal-height-col {
  height: 100%;
}

/* 卡片容器使用flex布局，让内部卡片平均分配高度 */
.card-group {
  height: 100%;
}

/* 让卡片高度充满父容器 */
.h-full {
  height: 100%;
}

/* 原有样式保持不变 */
.box-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.box-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
}

.card-header {
  font-size: 14px;
  font-weight: 500;
}

.large-money {
  font-size: 24px;
  font-weight: 500;
  margin: 10px 0;
  color: #000000A6;
}

.small-text {
  font-size: 13px;
  color: #666;
}

.sub-info {
  margin-top: 15px;
  font-size: 13px;
  color: #666;
  line-height: 1.6;
}

.mt-2 {
  margin-top: 8px;
}

/* flex布局相关样式 */
.flex {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.gap-4 {
  gap: 16px;
}

.flex-1 {
  flex: 1;
}

.chart-container {
  width: 100%;
  height: 380px; /* 明确设置高度，这是解决问题的关键 */
  min-height: 150px; /* 确保有最小高度 */
}

:deep(.el-card__header) {
  border-bottom: none !important; // 移除头部下边框
  padding-bottom: 0; // 可选：调整头部底部内边距
}
:deep(.el-card) {
  border-radius: 10px !important; // 可根据需要调整数值，越大圆角越明显
  overflow: hidden; // 确保卡片内容不会超出圆角范围
}
</style>

